/*************************************************
 Copyright (C), 2018, NanJu Tech. Co., Ltd.
 Author:       wunan
 Version:      1.0
 Date:         2018/9/10
 Description:  微信接入API
 Others:       
 History:      
 *************************************************/
package com.yantong.controller.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yantong.annotation.Auth;
import com.yantong.enums.MarketingGroupRulesEnum;
import com.yantong.enums.MarketingGroupTypeEnum;
import com.yantong.mapper.*;
import com.yantong.pojo.*;
import com.yantong.pojo.vo.*;
import com.yantong.service.*;
import com.yantong.constant.BusinessCode;
import com.yantong.constant.ProductType;
import com.yantong.controller.BaseController;
import com.yantong.exception.BDException;
import com.yantong.result.ResultVo;
import com.yantong.utils.ObjectUtils;
import com.yantong.utils.PageUtils;
import com.yantong.utils.ValidateUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@ApiIgnore
@Controller
@RequestMapping("/wxapi/marketing")
public class ApiMarketingController extends BaseController {


	@Autowired
	private MemberService memberService;
	@Autowired
	private ProductCentreService productCentreService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private TicketService ticketService;
	@Autowired
	private OrderProductMapper orderProductMapper;
	@Autowired
	private ProjectExpService projectExpService;
	@Autowired
	CardService cardService;
	@Autowired
    StringRedisTemplate redisTemplate;
	@Autowired
	ProductCommentService productCommentService;
	@Autowired
	PayChannelService payChannelService;
	@Autowired
	HeadTabService headTabService;
	@Autowired
	private MarketingSeckillService marketingSeckillService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private ActivityMapper activityMapper;
	@Autowired
	private ActivityProductMapper activityProductMapper;
	@Autowired
	private MarketingGroupService marketingGroupService;
	@Autowired
	private StoreFreechargeMapper storeFreechargeMapper;

	@Value("${spring.redis.host}")
	private String host;

	@Value("${spring.redis.port}")
	private int port = 6379;

	@Value("${spring.redis.timeout}")
	private int timeout = 0;

	@Value("${spring.redis.password}")
	private String password;

	private static final Logger logger = LoggerFactory.getLogger(ApiMarketingController.class);




	/**
	 * 获取商品列表
	 *
	 * @author kanghaixin
	 * @date 2018/9/7.15:39
	 */
	@RequestMapping("/products/group")
	@ResponseBody
	public ResultVo getMarketingGroup(ApiMarketingGroupReqVo reqVo, Integer offset, Integer limit) {
		logger.info("centerid==={} , teamid===={} , mid===={} , shop===={} ",reqVo.getCentreId(),reqVo.getTeamId(),reqVo.getMid(),reqVo.getShowType());
		PageUtils<ApiMarketingGroupResVo> products = marketingGroupService.listAllGroupForFront(offset, limit, reqVo);
		ResultVo resultVo = new ResultVo();
		resultVo.put("success", true);
		resultVo.put("data", products);
		return resultVo;
	}


	/**
	 * 获取商品拼团详情列表
	 *
	 * @author kanghaixin
	 * @date 2018/9/7.15:39
	 */
	@RequestMapping("/products/group/detail")
	@ResponseBody
	public ResultVo getMarketingGroupDetail(Long memberId, Long orderId, Long activityId) throws IllegalAccessException {
		ApiMarketingGroupResVo seckillResVo = marketingGroupService.getMarketingGroupDetail(memberId, activityId, orderId);
		seckillResVo.setProductType(ProductType.Spellgroup.getType());
		Long productId = seckillResVo.getProductId();

		//查询最新的评论
		ProductCommentVo commentVo = productCommentService.getNewComentByProductId(productId);
		seckillResVo.setComent(commentVo);
		seckillResVo.setComentCount(productCommentService.countComentCountByProductId(productId));
		CommanerVo vo = memberService.getCommanderByMembId(memberId);//通过会员Id查询门店信息
		//门店id
		CommanerVo liansuoVo = memberService.getCommanderByMembId(seckillResVo.getLiansuoid());//通过会员Id查询门店信息
		if (null != liansuoVo) {
			seckillResVo.setLiansuoVo(liansuoVo);
		}

		//分佣计算展示,创客/普通会员
		BigDecimal chuangkeCommission1 = BigDecimal.ZERO;
		BigDecimal chuangkeCommission2 = BigDecimal.ZERO;

		BigDecimal generalCommission1 = BigDecimal.ZERO;
		BigDecimal generalCommission2 = BigDecimal.ZERO;

		//查询拼团活动信息
		if (MarketingGroupTypeEnum.GIFT_BAG.getCode().equals(seckillResVo.getMarketingGroupType())) {
			ActivityProductExample example = new ActivityProductExample();
			example.createCriteria().andActivityIdEqualTo(seckillResVo.getProductId());
			List<ActivityProduct> activityProductList = activityProductMapper.selectByExample(example);
			if (ValidateUtil.isNotEmptyCollection(activityProductList)) {
				for (ActivityProduct activityProductTemp : activityProductList) {
					//门店ID
					Long shopMid = activityProductTemp.getProductId();
					if (null != shopMid) {
						List<StoreFreecharge> storeFreechargeList = null;
						List<String> list = new ArrayList<>();
						if (ValidateUtil.isNotEmptyString(activityProductTemp.getCouponIds())) {
							Collections.addAll(list, activityProductTemp.getCouponIds().split(","));
							storeFreechargeList = storeFreechargeMapper.selectByIdInStoreFreecharge(list);
						}
						if (storeFreechargeList != null) {
							//循环优惠券列表，将优惠券每张都发给用户，并且，parentID设置为上面插入的记录
							for (StoreFreecharge storeFreechargeInfo : storeFreechargeList) {
								Ticket ticket = ticketService.getByKey(storeFreechargeInfo.getRefId());
								//拼团发起人分佣
								Double sponsorCommission = seckillResVo.getInitiatorCommission();
								Double generalMemberCommission = seckillResVo.getGeneralMemberCommission();
								if (sponsorCommission != null && sponsorCommission > 0) {
									double ratio = sponsorCommission / 100;
									BigDecimal commissionSponsor = ticket.getBigGiftAmount().multiply(BigDecimal.valueOf(ratio)).setScale(2, BigDecimal.ROUND_DOWN);
									if (commissionSponsor.compareTo(BigDecimal.ZERO) > 0) {
										chuangkeCommission1 = chuangkeCommission1.add(commissionSponsor);
									}
								}

								if (generalMemberCommission != null && generalMemberCommission > 0) {
									double ratio = generalMemberCommission / 100;
									BigDecimal commissionGeneralMember = ticket.getBigGiftAmount().multiply(BigDecimal.valueOf(ratio)).setScale(2, BigDecimal.ROUND_DOWN);
									if (commissionGeneralMember.compareTo(BigDecimal.ZERO) > 0) {
										generalCommission1 = generalCommission1.add(commissionGeneralMember);
									}
								}
							}
						}
					}
				}
			}
		} else {
			//拼团发起人分佣
			Double sponsorCommission = seckillResVo.getInitiatorCommission();
			Double generalMemberCommission = seckillResVo.getGeneralMemberCommission();
			if (sponsorCommission != null && sponsorCommission > 0) {
				double ratio = sponsorCommission / 100;
				BigDecimal commissionSponsor = seckillResVo.getVipPrice().multiply(BigDecimal.valueOf(ratio)).setScale(2, BigDecimal.ROUND_DOWN);
				if (commissionSponsor.compareTo(BigDecimal.ZERO) > 0) {
					chuangkeCommission1 = chuangkeCommission1.add(commissionSponsor);
				}

				BigDecimal commissionSponsor2 = seckillResVo.getGroupPrice().multiply(BigDecimal.valueOf(ratio)).setScale(2, BigDecimal.ROUND_DOWN);
				if (commissionSponsor2.compareTo(BigDecimal.ZERO) > 0) {
					chuangkeCommission2 = chuangkeCommission2.add(commissionSponsor2);
				}
			}
			if (generalMemberCommission != null && generalMemberCommission > 0) {
				double ratio = generalMemberCommission / 100;
				BigDecimal commissionGeneralMember = seckillResVo.getVipPrice().multiply(BigDecimal.valueOf(ratio)).setScale(2, BigDecimal.ROUND_DOWN);
				if (commissionGeneralMember.compareTo(BigDecimal.ZERO) > 0) {
					generalCommission1 = generalCommission1.add(commissionGeneralMember);
				}
				BigDecimal commissionGeneralMember2 = seckillResVo.getGroupPrice().multiply(BigDecimal.valueOf(ratio)).setScale(2, BigDecimal.ROUND_DOWN);
				if (commissionGeneralMember2.compareTo(BigDecimal.ZERO) > 0) {
					generalCommission2 = generalCommission2.add(commissionGeneralMember2);
				}
			}
		}
		seckillResVo.setChuangkeCommission1(chuangkeCommission1);
		seckillResVo.setChuangkeCommission2(chuangkeCommission2);
		seckillResVo.setGeneralCommission1(generalCommission1);
		seckillResVo.setGeneralCommission2(generalCommission2);
		JSONObject jsonObject = (JSONObject) JSON.toJSON(seckillResVo);
		String s = redisTemplate.opsForValue().get("cardTotal:" + memberId + ":" + productId);
		String s1 = s == null ? "0" : s;
		jsonObject.put("cartNum", Integer.parseInt(s1));
		if (vo != null) {
			jsonObject.putAll(ObjectUtils.objectToMap(vo));
		}

		ResultVo resultVo = new ResultVo();
		resultVo.put("success", true);
		resultVo.put("data", jsonObject);
		resultVo.put("time", System.currentTimeMillis());
		return resultVo;
	}

	@ApiOperation(value = "拼团大礼包通兑券用户下单选择门店")
	@ResponseBody
	@GetMapping("/usable")
	public ResultVo marketingUsable(Long id) {
		List<TicketUsableTeam> ticketUsableTeam = null;
		//查询拼团活动信息
		MarketingGroup marketingGroup = marketingGroupService.getMarketingGroupById(id);
		if (MarketingGroupTypeEnum.GIFT_BAG.getCode().equals(marketingGroup.getMarketingGroupType())) {
			ticketUsableTeam = activityService.getTicketUsableTeam(marketingGroup.getProductId());
		}
		ResultVo resultVo = new ResultVo();
		resultVo.put("success", true);
		resultVo.put("data", ticketUsableTeam);
		return resultVo;
	}

	/**
	 * 订单预处理提交
	 */
	@RequestMapping("/seckill/order/precreate")
	@ResponseBody
	@Auth
	public ResultVo getSeckillOrderPreCreateInfo(@RequestBody OrderReq req) {
		ResultVo resultVo = precreate(req, ProductType.Miaosha.getType());
		return resultVo;
	}

	/**
	 * 订单预处理提交
	 */
	@RequestMapping("/group/order/precreate")
	@ResponseBody
	public ResultVo getGruopOrderPreCreateInfo(@RequestBody OrderReq req) {
		ResultVo resultVo = precreate(req, ProductType.Spellgroup.getType());
		return resultVo;
	}

	/**
	 * 提交订单
	 */
	@RequestMapping("/group/order/create")
	@ResponseBody
	@Auth
	public ResultVo createGroupOrder(@RequestBody @Valid MarketingBuyReq req) throws ParseException {
		long start = System.currentTimeMillis();
		req.setIsSubimtOrgType(2);
		req.setOrderType(ProductType.Spellgroup.getType());
		String orderId = orderService.submitOrderMarketing(req);
		ResultVo resultVo = new ResultVo();

		if ((orderId == null) || (orderId == "")) {
			resultVo.put("msg", "订单创建失败");
		} else {
			resultVo.put("success", true);
			resultVo.put("data", orderId);
		}
		logger.info("下单耗费时间：{}", System.currentTimeMillis() - start);
		return resultVo;
	}


	/**
	 * 秒杀 、团购 订单预处理
	 *
	 * @param req
	 * @param orderType 1: 秒杀 2：团购
	 * @return
	 */
	private ResultVo precreate(OrderReq req, Integer orderType) {
		ResultVo resultVo = new ResultVo();
		if (ProductType.Spellgroup.getType() == orderType) {
			req.setIsSpellgroup(1);
			//拼团订单不是发起人
			if (req.getOrderId() != null) {
				SpellGroupOrdVo vo = new SpellGroupOrdVo();
				vo.setMid(req.getMemberId());
				vo.setSgorderId(req.getOrderId());
				//查询是否参团
				List<Order> list = orderService.getSpellGroupOrdByMid(vo);
				if (CollectionUtils.isNotEmpty(list)) {
					//已参团
					return ResultVo.error("亲,你已参加过此团");
				}
			} else {
				resultVo.put("orderId", req.getOrderId());
				resultVo.put("type", req.getType());
			}
		}
		long start = System.currentTimeMillis();
		List<OrderProduct> orderProducts = new ArrayList<>();
		List<ProductCentre> productList = new ArrayList<>();
		List<Activity> activityList = new ArrayList<>();
		if (req.getIsCentreord() == null || req.getIsCentreord() == 0) {
			orderProducts = new ArrayList<>(req.getProducts().size());
			productList = new ArrayList<>(req.getProducts().size());
		}
		boolean overTime = false;
		boolean limit = false;
		BigDecimal postage = BigDecimal.ZERO;//运费
		BigDecimal alldweight = BigDecimal.ZERO;//所有的重量
		BigDecimal allPrice = BigDecimal.ZERO;//所有的价格
		BigDecimal vipPrice = null;
		if (req.getIsCentreord() == null || req.getIsCentreord() == 0) {
			Member member = memberService.getByKey(req.getMemberId());
			for (MemberCartVo cart : req.getProducts()) {
				boolean giftBagFlag = false;
				if (ProductType.Spellgroup.getType() == orderType && MarketingGroupTypeEnum.GIFT_BAG.getCode().equals(req.getMarketingGroupType())) {
					giftBagFlag = true;
				}

				ProductCentre productDetail = new ProductCentre();
				Activity activity = new Activity();
				if (giftBagFlag) {
					activity = activityMapper.selectByPrimaryKey(cart.getProductId());
					if (activity == null) {
						throw new BDException(BusinessCode.ORDER_PRODUCTS_ERROR);
					}

					activity.setProductName(activity.getActivityName());
				} else {
					productDetail = productCentreService.getByKeyWithCache(cart.getProductId());
					if (productDetail == null) {
						throw new BDException(BusinessCode.ORDER_PRODUCTS_ERROR);
					}

					//如果商品分类设置了商品类别。
					if (productDetail.getPcate() != null && productDetail.getPcate() != 0L) {
						Category category = categoryService.getByKey(productDetail.getPcate());
						req.setProductGradeId(category.getProductGradeId());
					}
				}

				if (!giftBagFlag && productDetail.getIsbig() == 0) {//只有不包邮的商品，才统计计算邮费
					alldweight = alldweight.add(productDetail.getWeight());//重量叠加
				}
				//价格叠加
				BigDecimal totalMarketPrice = cart.getMarketprice().multiply(new BigDecimal(cart.getTotal()));
				BigDecimal marketPrice = giftBagFlag ? activity.getActivityPrice() : productDetail.getMarketprice();

				//限购所需订单查询条件构建
				ListOrderParams orderParams = new ListOrderParams();
				orderParams.setMid(req.getMemberId());
				orderParams.setActivityId(req.getActivityId());

				if (ProductType.Spellgroup.getType() == orderType) {
					MarketingGroup marketingGroup = marketingGroupService.getMarketingGroupById(req.getActivityId());
					if (null != marketingGroup) {
						productDetail.setSales(marketingGroup.getSales());
						orderParams.setOrderType(ProductType.Spellgroup.getType());
						int orderCount = orderProductMapper.getByCount(orderParams);
						//限购数量
						if (marketingGroup.getPurchasingCount() != null && marketingGroup.getPurchasingCount() != 0) {
							if ((cart.getTotal() + orderCount) > marketingGroup.getPurchasingCount()) {
								throw new BDException(giftBagFlag ? activity.getActivityName() : productDetail.getShortTitle() + "限购" + marketingGroup.getPurchasingCount() + "份");
							}
						}

						//多规格商品，从sku中取价格
						if (!giftBagFlag && productDetail.getHasoption() != null && productDetail.getHasoption() == 1) {
							MarketingGroupSku marketingGroupSku = marketingGroupService.getSkuBySpecs(req.getActivityId(), cart.getSpecs());
							if (null != marketingGroupSku) {
								marketPrice = marketingGroupSku.getGroupPrice();
								if (marketingGroup.getType() == 1 && MarketingGroupRulesEnum.MISS.getCode().equals(req.getGroupRules())) {
									totalMarketPrice = BigDecimal.ZERO;
								} else {
									if (member.getIsVip() == 1 && marketingGroupSku.getVipPrice() != null) {
										//总价格=单价*数量
										totalMarketPrice = marketingGroupSku.getVipPrice().multiply(new BigDecimal(cart.getTotal()));
										vipPrice = marketingGroupSku.getVipPrice();
									} else {
										totalMarketPrice = marketingGroupSku.getGroupPrice().multiply(new BigDecimal(cart.getTotal()));
									}
								}
							}
							productDetail.setSkuId(marketingGroupSku.getSkuId());

							List<MarketingGroupSku> skus = marketingGroupService.getSkuByActivityId(req.getActivityId());

							if (ValidateUtil.isNotEmptyCollection(skus)) {
								List<ProductSkuCentre> skuList = new ArrayList<>();
								for (MarketingGroupSku skuitem : skus) {
									ProductSkuCentre skuCentre = new ProductSkuCentre();
									BeanUtils.copyProperties(skuitem, skuCentre);
									skuCentre.setMarketprice(skuitem.getGroupPrice());
									skuList.add(skuCentre);
									if (cart.getSpecs().equals(skuitem.getSpecs())) {
										productDetail.setTotal(skuitem.getStock());
									}
								}
								productDetail.setSkus(skuList);
							}
						}
						//非多规格商品，直接取拼团价格
						else {
							marketPrice = marketingGroup.getGroupPrice();
							productDetail.setTotal(marketingGroup.getStock());

							if (marketingGroup.getType() == 1 && MarketingGroupRulesEnum.MISS.getCode().equals(req.getGroupRules())) {
								totalMarketPrice = BigDecimal.ZERO;
							} else {
								if (member.getIsVip() == 1 && marketingGroup.getVipPrice() != null) {
									//总价格=单价*数量
									totalMarketPrice = marketingGroup.getVipPrice().multiply(new BigDecimal(cart.getTotal()));
									vipPrice = marketingGroup.getVipPrice();
								} else {
									totalMarketPrice = marketingGroup.getGroupPrice().multiply(new BigDecimal(cart.getTotal()));
								}
							}
						}

					}
				}
				allPrice = allPrice.add(totalMarketPrice);

				//规格项
				if (StringUtils.isNotEmpty(cart.getSpecs())) {
					ProductSkuCentre productSkuCentre = productCentreService.getSkuBySpecs(cart.getSpecs());
					if (productSkuCentre != null) {
						logger.info("============" + productDetail.getId() + productDetail.getTitle() + "======" + productSkuCentre.getId());
					} else {
						return ResultVo.error(productDetail.getTitle() + "-规格选择有误，请重试！");
					}
					productDetail.setCheckSkuTitle(productSkuCentre.getTitle());
					productDetail.setSkuId(productSkuCentre.getId());
					List<ProductSkuCentre> list = new ArrayList<>();
					list.add(productSkuCentre);
					productDetail.setSkus(list);
				}

				//校验时间 和库存
				marketingSeckillService.checkStockAndTime(req.getActivityId(), orderType, cart, req.getOrderId());


				if (!giftBagFlag && productDetail.getIsTeamBuy() == 1 && productDetail.getStartLimit() != null && cart.getTotal() < productDetail.getStartLimit()) {
					limit = true;
					continue;
				}
				if (!giftBagFlag && productDetail.getIsTeamBuy() == 1 && member.getIsteam() != 3) {
					continue;
				}

				cart.setCentreId(productDetail.getCentreId());
				if (giftBagFlag) {
					activity.setMarketprice(marketPrice);
					activityList.add(activity);
				} else {
					productDetail.setMarketprice(marketPrice);
					productList.add(productDetail);
				}


				OrderProduct orderProduct = new OrderProduct();
				orderProduct.setProductId(cart.getProductId());
				orderProduct.setSkuId(cart.getSkuId());
				orderProduct.setPrice(BigDecimal.valueOf(marketPrice.floatValue() * cart.getTotal()));
				orderProduct.setTotal(cart.getTotal());
				orderProduct.setIsKuaidi(productDetail.getIsKuaidi());
				orderProducts.add(orderProduct);
			}
		}

		req.setOrderType(orderType);
		List<TicketRecord> coupons = new ArrayList<TicketRecord>();
		BigDecimal discountPrice = BigDecimal.ZERO;
		if (req.getIsCentreord() != null && req.getIsCentreord() == 1) {
			overTime = true;
			limit = true;
			ProjectExpVo params = new ProjectExpVo();
			params.setType(0);
			params.setId(req.getProjectExpId());
			ProjectExp projectExp = projectExpService.listProjectExp(params);
			resultVo.put("data", projectExp);
			resultVo.put("isCentreord", req.getIsCentreord());
		} else {

			coupons = ticketService.getDetermineTicketRecords(req.getMemberId(), req.getProducts(), req.getTeamId(), req.getIndustryBrandId(), req.getProductGradeId(), req.getIndustryId());
			if (null != coupons && coupons.size() > 0) {
				coupons = coupons.stream().sorted(Comparator.comparing(TicketRecord::getAmount).reversed()).collect(Collectors.toList());
			}

			if (req.getCouponId() != null) {
				BigDecimal goodsPrice = BigDecimal.ZERO;
				List<ProductCentre> productCentreList = new ArrayList<>();
				Map<String, String> skuMap = new HashMap<>(16);
				for (MemberCartVo memberCartVo : req.getProducts()) {
					goodsPrice = goodsPrice.add(memberCartVo.getMarketprice());
					ProductCentre productCentre = productCentreService.getByKey(memberCartVo.getProductId());
					skuMap.put(productCentre.getId().toString(), memberCartVo.getSpecs());
					productCentreList.add(productCentre);
				}
				//计算优惠券金额
				discountPrice = orderService.calcTicketAmount(req.getCouponId(), goodsPrice, req.getCenterId(), productCentreList, req.getCateringType(), skuMap, postage);
				resultVo.put("couponPrice", discountPrice);
			} else {
				resultVo.put("couponPrice", BigDecimal.ZERO);
			}
		}
		resultVo.put("success", true);
		if (req.getIsCentreord() == null || req.getIsCentreord() == 0) {
			if (activityList.size() > 0) {
				resultVo.put("data", activityList);
			} else {
				resultVo.put("data", productList);
			}
		}

		resultVo.put("coupons", coupons);
		resultVo.put("overtime", overTime);
		resultVo.put("limit", limit);
		resultVo.put("postage", postage);
		resultVo.put("vipPrice", vipPrice);
		//价格
		resultVo.put("goodsPrice", allPrice);
		//订单总价
		BigDecimal orderPrice = allPrice.add(postage);
		resultVo.put("orderPrice", orderPrice);
		//实付金额
		BigDecimal payPrice = orderPrice;

		if (discountPrice.compareTo(BigDecimal.ZERO) > 0) {
			payPrice = payPrice.subtract(discountPrice);
		}
		resultVo.put("payPrice", payPrice);
		logger.info("预订单耗费时间：{}", System.currentTimeMillis() - start);
		return resultVo;
	}


}
